'''用户账户相关功能：注册、短信、登录、注销'''
from io import BytesIO

from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from utils.image_code import check_code
from web import models
from web.forms.account import ResigterModel, SendSmsForm, LoginSmsForm,LoginForm


def register_view(request):
    form = ResigterModel()
    if request.method == 'GET':
        return render(request, 'register.html', {'form': form})
    elif request.method == 'POST':
        form = ResigterModel(request.POST)
        print(request.POST)
        if form.is_valid():
            # 验证通过，写入数据库
            form.save()
            return JsonResponse({'status': True, 'data': '/login'})
        return JsonResponse({'status': False, 'error': form.errors})
    else:
        return HttpResponse('请求错误！')

def login_sms(request):
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    elif request.method == 'POST':
        form = LoginSmsForm(request.POST)
        if form.is_valid():
            user_object = form.cleaned_data['phone']
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60*60*24*14)
            # 正确的情况
            return JsonResponse({'status': True, 'data': '/index/'})
        return JsonResponse({'status': False, 'error': form.errors})
    else:
        return HttpResponse('请求错误！')

def login(request):
    '''用户名密码登录'''
    if request.method == 'GET':
        form=LoginForm(request)
        return render(request, 'login.html',{'form':form})
    elif request.method=='POST':
        form=LoginForm(request,data=request.POST)
        if form.is_valid():
            name=form.cleaned_data['name']
            pwd=form.cleaned_data['pwd']
            #user_object=models.WebUser.objects.filter(name=name,pwd=pwd).first()
            user_object=models.WebUser.objects.filter(Q(email=name)|Q(phone=name)).filter(pwd=pwd).first()
            if  user_object:
                request.session['user_id']=user_object.id
                request.session.set_expiry(60 * 60 * 24 * 14)
                return redirect('index')
            form.add_error('name','用户名或密码错误！')
        return render(request,'login.html',{'form':form})
    else:
        return HttpResponse('请求方式错误！')

def image_code(request):
    '''生成图片验证码'''
    image,code=check_code()
    '''图片验证码存入session'''
    request.session['image_code']=code
    request.session.set_expiry(60)#60s后session过期
    stream=BytesIO()
    image.save(stream,'png')
    return  HttpResponse(stream.getvalue())

def send_sms(request):
    '''发送短信'''
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        # 发送短信、写redis
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})
